package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.domain.CaseInsensitiveJSON;
import com.smart.village.big.screen.mapper.MicroSmartMoHeManagerMapper;
import com.smart.village.big.screen.service.MicroSmartMoHeManagerService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class MicroSmartMoHeManagerServiceImpl implements MicroSmartMoHeManagerService {
    @Resource
    private MicroSmartMoHeManagerMapper microSmartMoHeManagerMapper;
    @Override
    public JSONObject getHelpList(String townNumber, String villageNumber, String beginDate, String endDate, String iDCardNumber, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        if(StringUtils.isNotEmpty(status)){
            if (status.equals("处理中") ) {
                status = "0";
            }
            if (status.equals("已完成") ) {
                status = "未评价";
            }
            if (status.equals("已评价") ) {
                status = "已评价";
            }
        }

        List<JSONObject> list = microSmartMoHeManagerMapper.getHelpList(townNumber,villageNumber,beginDate,endDate,iDCardNumber,status);
        list.forEach(jsonObject -> {
            if("0".equals(jsonObject.getString("Row_Status"))){
                jsonObject.put("Row_Status_Name", "处理中");
            }

            if("2".equals(jsonObject.getString("Row_Status"))){
                if("已评价".equals(jsonObject.getString("Comment_Status"))){
                    jsonObject.put("Row_Status_Name", "已评价");
                }
                if("未评价".equals(jsonObject.getString("Comment_Status"))){
                    jsonObject.put("Row_Status_Name", "已完成");
                }
            }

        });
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getHelpListDetail(String applicationSerialNumber) {
        JSONObject jsonObject = microSmartMoHeManagerMapper.getHelpListDetail(applicationSerialNumber);
        List<JSONObject> attachList = microSmartMoHeManagerMapper.getApplyDetailAttachList(applicationSerialNumber);
        jsonObject.put("AttachList", attachList);
        List<JSONObject> replyList = microSmartMoHeManagerMapper.getHelpListDetailReplyList(applicationSerialNumber);
        jsonObject.put("ReplyList", replyList);
        replyList.forEach(reply -> {
            List<JSONObject> replyAttachList = microSmartMoHeManagerMapper.getHelpListDetailReplyAttachList(reply.getString("Application_Reply_SerialNumber"));
            reply.put("ReplyAttachList", replyAttachList);
        });
        return jsonObject;
    }

    @Override
    public JSONObject getLivelihoodDemandsList(String townNumber, String villageNumber,String Receiver, String beginDate, String endDate, String status,String ratingStatus,String parentCategorySerialNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = microSmartMoHeManagerMapper.getLivelihoodDemandsList(townNumber,villageNumber,Receiver,beginDate,endDate,status,ratingStatus,parentCategorySerialNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getLivelihoodDemandsDetail(String complaintId) {
        JSONObject jsonObject = microSmartMoHeManagerMapper.getLivelihoodDemandsDetail(complaintId);
        List<JSONObject> attachList = microSmartMoHeManagerMapper.getLivelihoodDemandsDetailAttachList(complaintId);
        jsonObject.put("AttachList", attachList);
        return jsonObject;
    }

    @Override
    public JSONObject getVillagerComplainsList(String townNumber, String villageNumber, String beginDate, String endDate, String replyStatus, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = microSmartMoHeManagerMapper.getVillagerComplainsList(townNumber,villageNumber,beginDate,endDate,replyStatus);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getVillagerComplainsDetail(String complaintId) {
        JSONObject jsonObject = microSmartMoHeManagerMapper.getVillagerComplainsDetail(complaintId);
        List<JSONObject> attachList = microSmartMoHeManagerMapper.getVillagerComplainsDetailAttachList(complaintId);
        jsonObject.put("AttachList", attachList);
        return jsonObject;
    }

    @Override
    public JSONObject getPatrolCheckInList(String iDCardNumber, String beginDate, String endDate, String taskStatus, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = microSmartMoHeManagerMapper.getPatrolCheckInList(iDCardNumber,beginDate,endDate,taskStatus);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getPatrolCheckInDetail(String taskPlanSerialNumber) {
        return microSmartMoHeManagerMapper.getPatrolCheckInDetail(taskPlanSerialNumber);
    }
    @Override
    public JSONObject getPatrolResultMainGridList(String taskPlanSerialNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = microSmartMoHeManagerMapper.getPatrolResultMainGridList(taskPlanSerialNumber);
        for (JSONObject jsonObject : list) {
            List<JSONObject> detailGridList = microSmartMoHeManagerMapper.getPatrolResultDetailGridList(jsonObject.getString("ResultMain_SerialNumber"));
            if(!CollectionUtils.isEmpty(detailGridList)){
                jsonObject.put("DetailGrid_List", detailGridList);
                jsonObject.put("If_Update_Status", "已上传");
            }else{
                jsonObject.put("DetailGrid_List", Lists.newArrayList());
                jsonObject.put("If_Update_Status", "未上传");
            }

        }

        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getPatrolResultDetailGridList(String resultMainSerialNumber) {
       return microSmartMoHeManagerMapper.getPatrolResultDetailGridList(resultMainSerialNumber);
    }
    @Override
    public List<JSONObject> getMyPatrolBorderListNoPage(String iDCardNumber) {
        return microSmartMoHeManagerMapper.getMyPatrolBorderList(iDCardNumber,"","","");
    }
    @Override
    public List<JSONObject> getComplaintsCategoriesFirstLevel(String iDCardNumber) {
        return microSmartMoHeManagerMapper.getComplaintsCategoriesFirstLevel(iDCardNumber);
    }

    @Override
    public List<JSONObject> getDeviceEnvironmentInformation(String iDCardNumber, String townNumber, String villageNumber) {
        return microSmartMoHeManagerMapper.getDeviceEnvironmentInformation(iDCardNumber,townNumber,villageNumber);
    }

    @Override
    public JSONObject getGarbageEnvironmentInformation(String iDCardNumber, String townNumber, String villageNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = microSmartMoHeManagerMapper.getGarbageEnvironmentInformation(iDCardNumber,townNumber,villageNumber);

        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getGarbageEnvironmentInformationDetail(String equipmentTaskDetailSerialNumber) {
        return microSmartMoHeManagerMapper.getGarbageEnvironmentInformationDetail(equipmentTaskDetailSerialNumber);
    }

    @Override
    public JSONObject getMyPatrolBorderCalendar(String iDCardNumber, String year, String month, String beginDate, String endDate) {

        JSONObject   result = new JSONObject();
        List<String> dates = new ArrayList<>();
        if(ObjectUtils.isEmpty(month)){
            month = LocalDate.now().getMonthValue() + "";
        }
        YearMonth yearMonth = YearMonth.of(Integer.parseInt(year), Integer.parseInt(month));
        int daysInMonth = yearMonth.lengthOfMonth();
        if(StringUtils.isNotEmpty(beginDate) || StringUtils.isNotEmpty(endDate)) {
            //获取传入的beginDate 到 endDate 的所有时间范围 放到 dates里
            LocalDate begin = LocalDate.parse(beginDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            while (!begin.isAfter(end)) {
                dates.add(begin.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                begin = begin.plusDays(1);
            }
            beginDate = dates.get(0);
            endDate = dates.get(dates.size()-1);
        }else{
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (int day = 1; day <= daysInMonth; day++) {
                LocalDate date = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), day);
                dates.add(date.format(formatter));
            }

                beginDate = dates.get(0);
                endDate = dates.get(dates.size()-1);

        }


        List<JSONObject> resultList = new ArrayList<>();
        List<JSONObject> myPatrolBorderList = microSmartMoHeManagerMapper.getMyPatrolBorderList(iDCardNumber, beginDate, endDate,"");
        for (String date : dates) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("date",date);
            jsonObject.put("status","0");
            for (JSONObject jsonObject1 : myPatrolBorderList) {
                if(date.equals(jsonObject1.getString("PlanDate"))){
                    if(jsonObject1.getString("Coord_Status").equals("已完成")){
                        jsonObject.put("status","2");
                    }else{
                        jsonObject.put("status","1");
                    }
                }
            }
            resultList.add(jsonObject);

        }
        result.put("monthData",resultList);
        result.put("totalCnt",myPatrolBorderList.size());
        result.put("finishCnt",myPatrolBorderList.stream().filter(item->item.getString("Coord_Status").equals("已完成")).count());
        return result;
    }

    @Override
    public JSONObject getMyPatrolBorderDetail(String taskPlanSerialNumber) {
        JSONObject myPatrolBorderDetail  = microSmartMoHeManagerMapper.getMyPatrolBorderDetail(taskPlanSerialNumber);
        List<JSONObject> resultMainList = microSmartMoHeManagerMapper.getMyPatrolBorderResultMain(taskPlanSerialNumber);
        myPatrolBorderDetail.put("ResultMainList",resultMainList);
        for (JSONObject jsonObject : resultMainList) {
            jsonObject.put("ResultDetailList",microSmartMoHeManagerMapper.getMyPatrolBorderResultDetail(jsonObject.getString("ResultMain_SerialNumber")));
        }
        List<JSONObject> myPatrolBorderResultCoord = microSmartMoHeManagerMapper.getMyPatrolBorderResultCoord(taskPlanSerialNumber);
        myPatrolBorderDetail.put("ResultCoordList",myPatrolBorderResultCoord);
        for (JSONObject jsonObject : myPatrolBorderResultCoord) {
            jsonObject.put("ResultCoordAttachmentList",microSmartMoHeManagerMapper.getMyPatrolBorderResultCoordAttachment(jsonObject.getString("Result_Coord_SerialNumber")));
        }
        return myPatrolBorderDetail;
    }

    @Override
    public List<JSONObject> getMyWillDoList(String iDCardNumber,String townNumber,String villageNumber, String beginDate, String endDate, String status) {


        String Livelihood = "";
        //status  待办理,已办理
        if(StringUtils.isNotEmpty(status)){
            if(status.equals("待办理")){
                Livelihood = "待办理";
            }
            if(status.equals("已办理")){
                Livelihood = "已办结";
            }
        }

        List<JSONObject> list1 = microSmartMoHeManagerMapper.getLivelihoodDemandsList(townNumber,villageNumber,iDCardNumber,beginDate,endDate,Livelihood,"","");


        if (!list1.isEmpty()) {
            list1 .forEach(jsonObject -> {
                List<JSONObject> firstComplaintCategories = microSmartMoHeManagerMapper.genFirstComplaintCategories(jsonObject.getString("category_id"));
                if(firstComplaintCategories.isEmpty()){
                    jsonObject.put("Type",jsonObject.getString("category_name"));
                }else {
                    jsonObject.put("Type", firstComplaintCategories.get(0).getString("category_name"));
                }
            });
        }
        String helpStatus = "";
        //status  "0" 处理中 "2" 已完成
        if(StringUtils.isNotEmpty(status)) {
            if (status.equals("待办理")) {
                helpStatus = "0";
            }
            if (status.equals("已办理")) {
                helpStatus = "2";
            }
        }
        List<JSONObject> list2 = microSmartMoHeManagerMapper.getHelpList(townNumber,villageNumber,beginDate,endDate,iDCardNumber,helpStatus);
        list2.forEach(jsonObject -> {
            if("0".equals(jsonObject.getString("Row_Status"))){
                jsonObject.put("Row_Status_Name", "处理中");
            }

            if("2".equals(jsonObject.getString("Row_Status"))){
                jsonObject.put("Row_Status_Name", "已完成");
            }
            jsonObject.put("Type","帮办代办");
        });

        list1.addAll(list2);

        String complaintStatus = "";
        //status 未回复 已回复
        if(StringUtils.isNotEmpty(status)) {
            if (status.equals("待办理")) {
                complaintStatus = "未回复";
            }
            if (status.equals("已办理")) {
                complaintStatus = "已回复";
            }
        }
        List<JSONObject> list3 = microSmartMoHeManagerMapper.getVillagerComplainsList(townNumber,villageNumber,beginDate,endDate,complaintStatus);
        list3.forEach(jsonObject -> {
            jsonObject.put("Type","留言回复");
        });
        list1.addAll(list3);


        String taskStatus = "";
        //taskStatus 未完成 已完成
        if(StringUtils.isNotEmpty(status)) {
            if (status.equals("待办理")) {
                taskStatus = "未完成";
            }
            if (status.equals("已办理")) {
                taskStatus = "已完成";
            }
        }
        List<JSONObject> list4 = microSmartMoHeManagerMapper.getPatrolCheckInList(iDCardNumber,beginDate,endDate,taskStatus);
        list4.forEach(jsonObject -> {
            jsonObject.put("Type","网格巡查");
        });
        list1.addAll(list4);

        list1.sort((o1, o2) -> {
            CaseInsensitiveJSON caseInsensitiveJSON1 = new CaseInsensitiveJSON(o1.toJSONString());
            CaseInsensitiveJSON caseInsensitiveJSON2 = new CaseInsensitiveJSON(o2.toJSONString());
            String createDatetime1 = String.valueOf(caseInsensitiveJSON1.get("Create_Datetime"));
            String createDatetime2 = String.valueOf(caseInsensitiveJSON2.get("Create_Datetime"));
            try {
                if(createDatetime1.length()>19){
                    createDatetime1 = createDatetime1.substring(0,19);
                }
                if(createDatetime2.length()>19){
                    createDatetime2 = createDatetime2.substring(0,19);
                }
                if(DateUtils.parseDate(createDatetime1,"yyyy-MM-dd HH:mm:ss").getTime()>DateUtils.parseDate(createDatetime2,"yyyy-MM-dd HH:mm:ss").getTime()){
                    return -1;
                }
            } catch (ParseException e) {
                return 1;
            }
            return 1;
        });

        return list1;
    }

    @Override
    public JSONObject getMyPatrolBorderList(String iDCardNumber, String beginDate, String endDate,String status, int pageNum, int pageSize) {

        List<JSONObject> list = microSmartMoHeManagerMapper.getMyPatrolBorderList(iDCardNumber,"","","已完成");

        int totalReportHaveCnt = 0;
        for (JSONObject object : list) {
            if (object.getString("Have_Report").equals("1")) {
                totalReportHaveCnt ++;
            }
        }


        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list1= microSmartMoHeManagerMapper.getMyPatrolBorderList(iDCardNumber,beginDate,endDate,status);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("totalReportNotHaveCnt", list.size()-totalReportHaveCnt);
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

}
